#include "keyboard.h"

KeyboardHandler::KeyboardHandler(void)
{

}

void KeyboardHandler::init(void)
{
	glfwSetKeyCallback(&keyHandler);
	glfwSetCharCallback(&charHandler);

}

KeyboardHandler::~KeyboardHandler(void)
{
	
}

void GLFWCALL keyHandler(int key, int action)
{
	if (action == GLFW_PRESS)
	{
		if (key == '<')
		{
			gameState->setConsoleDown(!gameState->isConsoleDown());
		}	
		
		if (!gameState->isConsoleDown())
		{
			/* muove il viewport */
			if (key == GLFW_KEY_UP)
			{
				gfxEngine->m_viewportY += 1.0f;
			}
			else if (key == GLFW_KEY_DOWN)
			{
				gfxEngine->m_viewportY -= 1.0f;
			}
			else if (key == GLFW_KEY_LEFT)
			{
				gfxEngine->m_viewportX -= 1.0f;
			}
			else if (key == GLFW_KEY_RIGHT)
			{
				gfxEngine->m_viewportX += 1.0f;
			}
			else if (key == GLFW_KEY_SPACE)
			{
				gamePlay->playerJumped(aPlayer);
			}
		}
		else
		{
			if (key == GLFW_KEY_BACKSPACE)
			{
				console->deleteChar();
			}
			else if (key == GLFW_KEY_ENTER)
			{
				console->appendChar(key);
			}
			else if (key == GLFW_KEY_TAB)
			{
				console->showHints();
			}
			else if (key == GLFW_KEY_UP)
			{
				console->nextUndoLine();
			}
			else if (key == GLFW_KEY_DOWN)
			{
				console->prevUndoLine();
			}
		}
	}
}

void GLFWCALL charHandler(int key, int action)
{
	/* se la console e' aperta tutti i tasti devono essere rediretti
	 * (a meno di qualche caso specifico tipo il menu principale
	 */

	if (gameState->isConsoleDown() && action == GLFW_PRESS)
	{
		if ((key >= 'A' && key <= 'Z') || (key >= 'a' && key <= 'z') || (key >= '0' && key <= '9') || key == ' ' || key == '^' || key == '_')
		{
			console->appendChar(key);
		}
	}
	else
	{
		if ((key == 'a'))
		{
			if (action == GLFW_PRESS)
				gamePlay->playerIsMoving(aPlayer, MOVE_LEFT);
			else if (action == GLFW_RELEASE)
				gamePlay->playerStopped(aPlayer, MOVE_LEFT);

		}
		else if ((key == 'd'))
		{
			if (action == GLFW_PRESS)
				gamePlay->playerIsMoving(aPlayer, MOVE_RIGHT);
			else if (action == GLFW_RELEASE)
				gamePlay->playerStopped(aPlayer, MOVE_RIGHT);

		}
	}
}

